import requests
import sys

from plugins.core.plugin import Plugin
from plugins.core.pluginvideo import PluginVideo
from plugins.core.pluginplaylist import PluginPlaylist
from src.history import History

sys.path.append("..")
from src.vobjects.item import Item

class SovetRomantica(Plugin):

    def __init__(self, history: History=History()):
        self.name = "SovetRomantica: Search"
        self.is_query_required = True
        self.query_description = """"""
        self.history = history

        self.flag = "-sr"
        self.full_flag = "--sovetromantica"
        self.flag_help = "search sovetromantica titles"
        self.flag_action = ""

    def get_episodes(self, anime_id):
        resp = requests.get(
            f"https://service.sovetromantica.com/v1/anime/{anime_id}/episodes" 
        )

        if resp.status_code != 200: return list()
        episodes = resp.json()

        return episodes

    def get_search(self, query: str=""):
        resp = requests.get("https://service.sovetromantica.com/v1/animesearch", 
            {
                "anime_name" : query
            }
        )

        if resp.status_code != 200: return list()
        anime_list = resp.json()

        items = []
        for it in anime_list:
            if type(it) != dict: continue
            title = f"{it['anime_name']} ({it['anime_name_russian']})"
            anime_id = it['anime_id']

            episodes = list()
            episodes_js = self.get_episodes(anime_id)
            for episode in episodes_js:
                if type(episode) != dict or episode['episode_type'] > 0: continue

                ititle = f"Episode {episode['episode_count']}"
                video = PluginVideo(
                    title=ititle,
                    playlist_title=title,
                    url=episode['embed']
                )

                inHistory = video.in_history(self.history)

                item = video.to_item(inHistory=inHistory)

                episodes.append(item)
            
            episodes.sort(key=lambda v: int(v.parent.title[8:]))
            playlist = PluginPlaylist(title, episodes)

            item = Item(
                title=title,
                fstr=f"{len(playlist.videos)} series",
                parent=playlist
            )

            items.append(item)

        return items

    def get_items_by_query(self, query: str=""):
        return self.get_search(query=query)

    def get_items(self):
        return list()

if __name__ == "__main__":
    sr = SovetRomantica()

    items = sr.get_items_by_query(query="мастера меча онлайн")
    for item in items:
        print(item.title, item.parent.url)




